package com.price.httplib.core

import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.ResponseBody
import okhttp3.ResponseBody.Companion.toResponseBody
import retrofit2.Converter
import retrofit2.Retrofit
import java.lang.reflect.Type

class NullOnEmptyConverterFactory : Converter.Factory() {

    override fun responseBodyConverter(
        type: Type,
        annotations: Array<out Annotation>,
        retrofit: Retrofit
    ): Converter<ResponseBody, *> {
        val delegate: Converter<ResponseBody, *> =
            retrofit.nextResponseBodyConverter<Any>(this, type, annotations)
        return Converter<ResponseBody, Any?> { body ->
            if (body.contentLength() == 0L) {
                val mediaType = "application/json;charset=utf-8".toMediaTypeOrNull()
                val newBody ="{\"code\":200,\"msg\":\"body is empty\"}".toResponseBody(mediaType)
                return@Converter delegate.convert(newBody)
            }
            delegate.convert(body)
        }
//        return super.responseBodyConverter(type, annotations, retrofit)
    }
}